//
//  InvestPayViewController.m
//  Kjs-iOS
//
//  Created by cfq on 16/6/1.
//  Copyright © 2016年 jmhz. All rights reserved.
//

#import "InvestPayViewController.h"
#import "MapRadioButton.h"
#import "UIColor+KjsColor.h"
#import "CommonUtil.h"
#import "KJSRequest.h"
#import "AppDelegate.h"
#import "PayOrderModel.h"
#import "ProtocolViewController.h"

#define CodeTimeInterval 180
typedef NS_ENUM(NSInteger,PayOrderMode)
{
    xianxia = 0,
    wangyin
};

@interface InvestPayViewController()<MapRadioButtonDelegate,UIActionSheetDelegate>

@property (weak, nonatomic) IBOutlet UIView *payTypeView;

@property (nonatomic,weak) IBOutlet UILabel *itemNameLab;
@property (nonatomic,weak) IBOutlet UILabel *gdAnnualizedBenefitRateLab;
@property (nonatomic,weak) IBOutlet UILabel *interestDaysLab;
@property (nonatomic,weak) IBOutlet UILabel *remindMoneyLab;
@property (weak,nonatomic) IBOutlet UILabel *gdBenefitModeLab;

@property (weak,nonatomic) IBOutlet UITextField *totalPrice;
@property (weak,nonatomic) IBOutlet UITextField *code;
@property (weak,nonatomic) IBOutlet UITextField *tradePwd;

@property (nonatomic,weak) IBOutlet UIButton *investBtn;
@property (nonatomic,weak) IBOutlet UIButton *sendCondeBtn;

@property (nonatomic,strong) NSString *payModeName;
@property (nonatomic,strong) PayOrderModel *payOrderModel;

@property (nonatomic,assign) int secondsCountDown;//倒计时总时长
@property (nonatomic,strong) NSTimer *countDownTimer;
@end

@implementation InvestPayViewController
-(void)viewDidLoad{

    self.navigationItem.title = @"投资支付";
    self.investBtn.layer.cornerRadius = 10;
    self.investBtn.layer.masksToBounds = YES;
    self.sendCondeBtn.layer.cornerRadius = 10;
    self.sendCondeBtn.layer.masksToBounds = YES;
    self.tradePwd.secureTextEntry = YES;
    self.secondsCountDown = CodeTimeInterval;
    //获取投资协议按钮
    UIButton* rightButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightButton.titleLabel.font=[UIFont systemFontOfSize:14];
    [rightButton setTitle:@"协议" forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(GetInvestPto) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBtn;
    
    
    MapRadioButton *radio1 = [[MapRadioButton alloc] initWithDelegate:self groupId:@"groupId1"];
    radio1.frame = CGRectMake(80, 11, 80, 21);
    [radio1 setTitle:@"线下支付" forState:UIControlStateNormal];
    [radio1 setTitleColor:[UIColor kjsMidGrayColor] forState:UIControlStateNormal];
    [radio1.titleLabel setFont:[UIFont boldSystemFontOfSize:13.0f]];
    radio1.tag = xianxia;
    [self.payTypeView addSubview:radio1];
    [radio1 setChecked:YES];
    
//    MapRadioButton *radio2 = [[MapRadioButton alloc] initWithDelegate:self groupId:@"groupId1"];
//    radio2.frame = CGRectMake(150, 11, 80, 21);
//    [radio2 setTitle:@"网银支付" forState:UIControlStateNormal];
//    [radio2 setTitleColor:[UIColor kjsMidGrayColor] forState:UIControlStateNormal];
//    [radio2.titleLabel setFont:[UIFont boldSystemFontOfSize:13.0f]];
//    radio2.tag = wangyin;
//    [self.payTypeView addSubview:radio2];
//    self.investBtn.layer.cornerRadius = 10;
    
    self.itemNameLab.text = [NSString stringWithFormat:@"%@",self.item.itemName];
    self.gdAnnualizedBenefitRateLab.text = [NSString stringWithFormat:@"%.2lf％",self.item.gdAnnualizedBenefitRate * 100];
    self.interestDaysLab.text = [NSString stringWithFormat:@"%d天",self.item.interestDays];
    self.gdBenefitModeLab.text = [CommonUtil getGdBenefitModeStrWithMode:self.item.gdBenefitMode];

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString *remindMoneyStr = [formatter stringFromNumber:[NSNumber numberWithDouble:(self.item.targetMoney - self.item.raiseMoney)]];
    self.remindMoneyLab.text = [NSString stringWithFormat:@"¥%@",remindMoneyStr];
    
    [self.investBtn addTarget:self action:@selector(SubmitOrder) forControlEvents:UIControlEventTouchUpInside];
    [self.sendCondeBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    
    self.payModeName = [self getPayModeNameStrWithRow:0];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.payOrderModel = [[PayOrderModel alloc] init];
}
#pragma mark - custom method
-(void)PayOrder
{
    if (CurentDelegate.account) {
        NSLog(@"code=%@,partyId=%@,itemId=%@,totalPrice=%@,tradepsw=%@,mode=%@",self.code.text,CurentDelegate.account.partyId,self.item.itemId,self.totalPrice.text,self.tradePwd.text,self.payModeName);
        [KJSRequest PayOrderWithVerificationCode:self.code.text partyId:CurentDelegate.account.partyId itemId:self.item.itemId totalPrice:self.totalPrice.text tradePwd:self.tradePwd.text orderPayModeNamePinYin:self.payModeName bankCardId:@"" comments:@"" ret:^(PayOrderModel *model) {
            self.payOrderModel = model;
            if (self.payOrderModel.success == true) {
                [GUATool showDialog:@"投资成功" message:nil waitingTime:1.5];
                [self dismiss:YES];
                [self performSelector:@selector(investSuccessReturnFunc) withObject:nil afterDelay:1.5f];
                
            }
        }];
    }else{
        NSLog(@"未登录");
    }

}
-(void)investSuccessReturnFunc
{
    if (self.investSuccess) {
        self.investSuccess([self.totalPrice.text doubleValue]);
    }
}
-(void)sendMessage
{
    if (CurentDelegate.account.phoneNumber) {
        if ([CurentDelegate.account.type isEqualToString:@"n"]) {
            [GUATool showDialog:@"请先进行实名认证" message:nil waitingTime:1.5];
        }else{
            [KJSRequest PayOrderSendMessageWithPhoneNumber:CurentDelegate.account.phoneNumber sendName:CurentDelegate.account.nickName  ret:^(BasicResult *model) {
                if ([model.messageresult isEqualToString:@"0"]) {
                    [GUATool showDialog:@"验证码发送成功" message:nil waitingTime:1.5];
                    self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
                }
            }];
        }
    }else{
        [GUATool showDialog:@"请先绑定手机号" message:nil waitingTime:1.5];
    }
}
-(void)timeFireMethod{
    
    self.secondsCountDown--;
    self.sendCondeBtn.titleLabel.text = [NSString stringWithFormat:@"%d秒",self.secondsCountDown];
    [self.sendCondeBtn setTitle:[NSString stringWithFormat:@"%d秒",self.secondsCountDown] forState:UIControlStateNormal];
    self.sendCondeBtn.enabled = NO;
    if (self.secondsCountDown == 0) {
        [self.countDownTimer invalidate];
        [self.sendCondeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.sendCondeBtn.enabled = YES;
        self.secondsCountDown = CodeTimeInterval;
    }
}

-(void)GetInvestPto
{

    if (self.item.gdItemType == 2) {
       
    }
    switch (self.item.gdItemType) {
        case 2:
        {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"协议" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil,nil];
            for(int j=0;j<[WQZYDPro count];j++)
            {
                NSString *str=[[NSString alloc]initWithFormat:@"%@",[WQZYDPro objectAtIndex:j]];
                [sheet addButtonWithTitle:str];
            }
            [sheet showInView:self.view];
        }break;
        case 4:
        {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"协议" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil,nil];
            for(int j=0;j<[XFJRDPro count];j++)
            {
                NSString *str=[[NSString alloc]initWithFormat:@"%@",[XFJRDPro objectAtIndex:j]];
                [sheet addButtonWithTitle:str];
            }
            [sheet showInView:self.view];
        }
        default:
            break;
    }

}
-(NSString *)getPayModeNameStrWithRow:(NSInteger)row
{
    
    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"xianxiazhifu",@"wangyinzhifu",nil];
    if (row < [array count]) {
        return array[row];
    }else{
        return @"";
    }
    
}
- (void)SubmitOrder
{
    if ([self.code.text isEqualToString:@""]) {
        [GUATool showDialog:@"请输入验证码" message:nil waitingTime:1.5];
    }else if ([self.totalPrice.text isEqualToString:@""]){
        [GUATool showDialog:@"请输入投资金额" message:nil waitingTime:1.5];
    }else if ( self.itemPlan[0].lowLimitMoney > [self.totalPrice.text integerValue] ){
        [GUATool showDialog:@"投资金额应大于起投金额" message:nil waitingTime:1.5];
    }else if ( (([self.totalPrice.text doubleValue] - self.itemPlan[0].lowLimitMoney)/self.itemPlan[0].increaseMoney) !=  (int)(([self.totalPrice.text doubleValue] - self.itemPlan[0].lowLimitMoney)/self.itemPlan[0].increaseMoney) ){
        [GUATool showDialog:[NSString stringWithFormat:@"%.2lf的整数倍金额",self.itemPlan[0].increaseMoney] message:nil waitingTime:1.5];
    }
    else if ([self.tradePwd.text isEqualToString:@""]){
        [GUATool showDialog:@"请输入交易密码" message:nil waitingTime:1.5];
    }else{
        [self PayOrder];
    }
}
#pragma mark - UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"sheet clicked index = %ld",buttonIndex);
    if (buttonIndex != 0) {
        switch (self.item.gdItemType) {
            case 2:
            {
                NSLog(@"获取投资协议");
                ProtocolViewController *protocolVC = [[UIStoryboard storyboardWithName:@"Seconed" bundle:nil] instantiateViewControllerWithIdentifier:@"ProtocolViewController"];
                protocolVC.proType = [NSString stringWithFormat:@"%@",WQZYDProFlag[buttonIndex-1]];
                protocolVC.proTitle = WQZYDPro[buttonIndex-1];
                [self displayViewController:protocolVC];
            }
                break;
            case 4:
            {
                NSLog(@"获取投资协议");
                ProtocolViewController *protocolVC = [[UIStoryboard storyboardWithName:@"Seconed" bundle:nil] instantiateViewControllerWithIdentifier:@"ProtocolViewController"];
                protocolVC.proType = [NSString stringWithFormat:@"%@",XFJRDProFlag[buttonIndex-1]];
                protocolVC.proTitle = XFJRDPro[buttonIndex-1];
                [self displayViewController:protocolVC];
            }
                break;
                
            default:
                break;
        }
    }
}
@end
